/*
 * @Author: xushuhao
 * @Email: xshmouse@163.com
 * @Date: 2020-05-07 15:26:40
 * @Last Modified by: xushuhao
 * @Last Modified time: 2020-07-28 10:23:54
 * @Description: Description
 */

import 'dart:io';

import 'package:auto_orientation/auto_orientation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_sfsymbols/flutter_sfsymbols.dart';
import 'dart:core';
import 'dart:async';
import 'package:video_player/video_player.dart';
import 'package:orientation/orientation.dart';

class XVideoPlayer extends StatefulWidget {
  List<PlayerInputInstance> path = [];
  String type;
  String state;
  int currentValue;
  int curIndex;
  int curVideoTypeIndex;
  bool isFullScreen;
  bool isPlay;
  bool isMaxDisplay;
  String sourceType;
  Function backCall;

  XVideoPlayer(
      {Key key,
      this.path,
      this.type,
      this.currentValue = 0,
      this.curIndex = 0,
      this.curVideoTypeIndex = 0,
      this.isFullScreen = true,
      this.sourceType = 'network', //数据源类型 network 、 asset、 file
      this.isPlay = true, //默认自动播放
      this.isMaxDisplay = true, //默认小屏显示横屏按钮
      this.backCall})
      : super(key: key);

  @override
  State<StatefulWidget> createState() {
    return XVideoPlayerState();
  }
}

class XVideoPlayerState extends State<XVideoPlayer>
    with SingleTickerProviderStateMixin {
  int _currentIndex;
  int _currentValue;
  int _currentVideoTypeIndex;
  bool openPannel = false;
  Color sliderPointColor =
      Color.fromRGBO(236, 115, 100, 1); //Color.fromRGBO(234, 21, 19, 1);
  Color sliderUnusedColor = Color.fromRGBO(143, 146, 154, 1);
  AnimationController playerPannelController;
  Animation<double> playerTopPannelAnimation;
  Animation<double> playerTopPannelInfoAnimation;
  Animation<double> playerBottomPannelAnimation;
  Animation<double> playerBottomPannelInfoAnimation;
  static final playerTopPannelInfoTween = Tween<double>(begin: -56.0, end: 0.0);
  static final playerTopPannelTween = Tween<double>(begin: -86.0, end: 0.0);
  static final playerBottomPannelInfoTween =
      Tween<double>(begin: -64.0, end: 0.0);
  static final playerBottomPannelTween = Tween<double>(begin: -84.0, end: 0.0);

  //播放器
  VideoPlayerController palyerController;
  double topBackgroudValue, topValue, bottomValue;
  int videoAllTimes = 0;
  int timerNum = 0;
  var _currentHeadColor;
  //状态栏
  var osStateInfo = [SystemUiOverlay.top, SystemUiOverlay.bottom];
  //屏幕方向
  StreamSubscription<DeviceOrientation> subscription;
  DeviceOrientation _deviceOrientation;
  bool _isFullScreen;
  bool _operFullScreen = false;
  bool _openList = false;
  //清晰度列表
  OverlayEntry videoTypeListOverlay;
  bool isShowVideoTypeList = false;
  GlobalKey _tapButtonWidget = GlobalKey();
  //菜单
  bool isShowRightMenu = false;
  //分析
  bool isShowShareMenu = false;
  //播放状态
  bool isPlaying = false;

  @override
  Widget build(BuildContext context) {
    SystemChrome.setEnabledSystemUIOverlays(osStateInfo);

    Widget result;

    result = Stack(
      children: <Widget>[
        //player
        Center(
          child: palyerController.value.initialized
              ? AspectRatio(
                  aspectRatio: palyerController.value.aspectRatio,
                  child: Container(
                    color: Colors.black,
                    child: VideoPlayer(palyerController),
                  ),
                )
              : Container(
                  color: Colors.transparent,
                  child: Text(
                    'Loading.....',
                    style: TextStyle(color: Colors.white),
                  ),
                ),
        ),
        //top backgroud
        Positioned(
            top: playerTopPannelTween.evaluate(
                playerTopPannelAnimation), //playerTopPannelAnimation.value,
            child: Container(
              constraints: BoxConstraints.expand(
                  height: 86, width: MediaQuery.of(context).size.width),
              decoration: BoxDecoration(
                gradient: LinearGradient(
                  begin: Alignment.topCenter,
                  end: Alignment.bottomCenter,
                  colors: [
                    Color.fromRGBO(96, 96, 96, 0.7),
                    Color.fromRGBO(96, 96, 96, 0)
                  ],
                ),
              ),
            )),
        //bottom backgroup
        Positioned(
          bottom: playerBottomPannelTween.evaluate(playerBottomPannelAnimation),
          child: Container(
            constraints: BoxConstraints.expand(
                height: 84, width: MediaQuery.of(context).size.width),
            decoration: BoxDecoration(
              gradient: LinearGradient(
                begin: Alignment.bottomCenter,
                end: Alignment.topCenter,
                colors: [
                  Color.fromRGBO(96, 96, 96, 0.7),
                  Color.fromRGBO(96, 96, 96, 0)
                ],
              ),
            ),
          ),
        ),
        //touch area
        GestureDetector(
          child: Container(
            constraints: BoxConstraints.expand(),
            child: Text(''), //此处可放品牌水印，常在。
          ),
          onTap: () {
            operatePannel();
            setState(() {
              isShowVideoTypeList = false;
              isShowRightMenu = false;
            });
            print('单击');
          },
          onDoubleTap: () {
            print('双击');
            palyerController.value.isPlaying
                ? palyerController.pause()
                : palyerController.play();
          },
          // onHorizontalDragStart: (v) {
          //   print(
          //       '横向拖动开始=》位置：globalPosition=${v.globalPosition}  时间sourceTimeStamp= ${v.sourceTimeStamp.toString()}');
          // },
          // onHorizontalDragEnd: (v) {
          //   print(
          //       '横向拖动停止：primaryVelocity=${v.primaryVelocity}  速度velocity= ${v.velocity}');
          // },
          // onHorizontalDragUpdate: (v) {
          //   print(
          //       '横向拖动过程=》 delta=${v.delta.toString()} primaryDelta=${v.primaryDelta} globalPosition=${v.globalPosition}  sourceTimeStamp=${v.sourceTimeStamp}');
          // },
          // onVerticalDragStart: (v) {
          //   print(
          //       '纵向向拖动开始=》位置：globalPosition=${v.globalPosition}  时间sourceTimeStamp= ${v.sourceTimeStamp.toString()}');
          // },
          // onVerticalDragEnd: (v) {
          //   print(
          //       '纵向拖动停止：primaryVelocity=${v.primaryVelocity}  速度velocity= ${v.velocity}');
          // },
          // onVerticalDragUpdate: (v) {
          //   print(
          //       '纵向拖动过程=》 delta=${v.delta.toString()} primaryDelta=${v.primaryDelta} globalPosition=${v.globalPosition}  sourceTimeStamp=${v.sourceTimeStamp}');
          // },
        ),
        //top info
        Positioned(
          top: playerTopPannelInfoTween.evaluate(
              playerTopPannelInfoAnimation), //playerTopPannelInfoAnimation.value,
          child: Container(
              color: Colors.transparent,
              constraints: BoxConstraints.expand(
                  height: 56, width: MediaQuery.of(context).size.width),
              child: Padding(
                padding: EdgeInsets.fromLTRB(16, 30, 16, 0),
                child: Row(
                  crossAxisAlignment: CrossAxisAlignment.center,
                  children: <Widget>[
                    IconButton(
                      iconSize: 30, //热区
                      padding: EdgeInsets.all(0),
                      icon: Icon(
                        Icons.keyboard_arrow_left,
                        color: Colors.white,
                        size: 30,
                      ),
                      onPressed: () {
                        // print('return');
                        if (_isFullScreen) {
                          // AutoOrientation.fullAutoMode();
                          // widget.backCall(true);
                          AutoOrientation.portraitUpMode();
                          Navigator.of(context).pop();
                        } else {
                          if (_operFullScreen) {
                            widget.backCall(false);
                            setState(() {
                              _operFullScreen = false;
                            });
                          } else {
                            Navigator.of(context).pop();
                          }
                        }
                      },
                    ),
                    Expanded(
                      child: Container(
                        child: Padding(
                          padding: EdgeInsets.fromLTRB(10, 0, 10, 0),
                          child: Text(
                            widget.path[_currentIndex].title,
                            style: TextStyle(
                              color: Colors.white,
                              fontSize: 16,
                            ),
                            overflow: TextOverflow.ellipsis,
                          ),
                        ),
                      ),
                    ),
                    IconButton(
                      padding: EdgeInsets.all(0),
                      icon: Icon(
                        Icons.share,
                        color: Colors.transparent,
                        size: 26,
                      ),
                      onPressed: () {
                        print('share');
                      },
                    ),
                    Padding(
                      padding: EdgeInsets.fromLTRB(35, 0, 0, 0),
                      child: IconButton(
                        padding: EdgeInsets.all(0),
                        icon: Icon(
                          Icons.more_vert,
                          color: Colors.transparent,
                          size: 30,
                        ),
                        onPressed: () {
                          print('menu');
                          setState(() {
                            isShowRightMenu = true;
                          });
                        },
                      ),
                    ),
                  ],
                ),
              )),
        ),
        // //bottom info
        Positioned(
          bottom: playerBottomPannelInfoTween
              .evaluate(playerBottomPannelInfoAnimation),
          child: Container(
            color: Colors.transparent,
            constraints: BoxConstraints.expand(
                height: 64, width: MediaQuery.of(context).size.width),
            child: Padding(
              padding: EdgeInsets.fromLTRB(16, 0, 16, 0),
              child: Column(
                children: <Widget>[
                  SliderTheme(
                    data: SliderTheme.of(context).copyWith(
                      // activeTickMarkColor:Colors.yellowAccent,
                      activeTrackColor: sliderPointColor, //实际进度的颜色
                      // inactiveTickMarkColor:Colors.black
                      thumbColor: sliderPointColor, //滑块中心的颜色
                      inactiveTrackColor: sliderUnusedColor, //默认进度条的颜色
                      valueIndicatorColor:
                          Color.fromRGBO(57, 135, 110, 1), //提示进度的气泡的背景色
                      valueIndicatorTextStyle: TextStyle(
                        //提示气泡里面文字的样式
                        color: Colors.white,
                      ),
                      inactiveTickMarkColor:
                          Colors.blue, //divisions对进度线分割后 断续线中间间隔的颜色
                      overlayColor: Colors.red[200], //滑块边缘颜色
                    ),
                    child: Container(
                      // width: MediaQuery.of(context).size.width - 32,
                      // margin: EdgeInsets.all(0),
                      height: 15,
                      child: Row(
                        children: <Widget>[
                          // new Text('00:00'),
                          Expanded(
                            flex: 1,
                            child: Slider(
                              value: _currentValue.toDouble() ?? 0,
                              label: '当前秒:' + (_currentValue ?? 0).toString(),
                              divisions:
                                  (videoAllTimes == null || videoAllTimes == 0)
                                      ? 100
                                      : videoAllTimes,
                              onChangeEnd: (double v) {},
                              onChanged: (double v) {
                                // setState(() {
                                //   _currentValue = v.toInt();
                                // });
                                palyerController
                                    .seekTo(Duration(seconds: v.toInt()));
                              },
                              min: 0.0,
                              max: (videoAllTimes == 0)
                                  ? 99999
                                  : videoAllTimes.toDouble(),
                            ),
                          ),
                          // new Text('30:45'),
                        ],
                      ),
                    ),
                  ),
                  Row(
                    children: <Widget>[
                      Container(
                        width: 45,
                        child: FlatButton(
                          padding: EdgeInsets.all(0),
                          child: Icon(
                            palyerController.value.initialized
                                ? (palyerController.value.isPlaying
                                    ? Icons.pause
                                    : Icons.play_arrow)
                                : Icons.swap_vert,
                            size: 30,
                            color: Colors.white,
                          ),
                          onPressed: () {
                            palyerController.value.isPlaying
                                ? palyerController.pause()
                                : palyerController.play();
                            setState(() {});
                          },
                        ),
                      ),
                      Container(
                          width: 50,
                          child: FlatButton(
                            padding: EdgeInsets.all(0),
                            child: Icon(
                              Icons.skip_next,
                              color: Colors.transparent,
                              size: 20,
                            ),
                            onPressed: () {
                              print('object');
                            },
                          )),
                      Expanded(
                        child: Text(
                          '${(_currentValue ~/ 60).toString().padLeft(2, '0')}:${(_currentValue % 60).toString().padLeft(2, '0')}/${(videoAllTimes ~/ 60).toString().padLeft(2, '0')}:${(videoAllTimes % 60).toString().padLeft(2, '0')}',
                          style: TextStyle(color: Colors.white, fontSize: 12),
                        ),
                      ),
                      //清晰度按钮
                      getVideoTypeFunction(),
                      //选集按钮
                      getPlayerListFunction(),
                      //小屏时显示 横屏操作
                      getOrientationFunction(),
                    ],
                  )
                ],
              ),
            ),
          ),
        ),
        //播放列表
        getPlayerList(),
        //清晰度列表
        getVideTypeList(),
        //菜单列表
        getRightMenu(),
        //播放按钮
        getPlayButton(),
      ],
    );

    return Scaffold(
      //背景
      backgroundColor: Colors.black,
      body: Center(
        child: result,
      ),
    );
  }

  Widget getPlayButton() {
    Widget rs = Text('');
    if (!isPlaying && palyerController.value.initialized) {
      rs = GestureDetector(
        child: Center(
          child: Icon(
            SFSymbols.play_fill,
            size: 40,
            color: Color.fromRGBO(164, 164, 164, 1).withOpacity(0.5),
          ), //Color.fromRGBO(164, 164, 164, 1)
        ),
        onTap: () {
          if (!palyerController.value.isPlaying) {
            palyerController.play();
          }
        },
      );
    }
    return rs;
  }

  //右侧弹窗公共框架
  Widget getRightPopMenu(Widget child) {
    return Positioned(
      right: 0, //playerTopPannelInfoAnimation.value,
      child: Container(
        decoration: BoxDecoration(
          color: Colors.transparent, //Color.fromRGBO(0, 0, 0, 0.5),
          shape: BoxShape.rectangle,
          border: Border.all(color: Colors.transparent, width: 0),
          // gradient: LinearGradient(colors: [
          //   Color.fromRGBO(0, 0, 0, 0.5),
          //   Color.fromRGBO(0, 0, 0, 0.4),
          // ], begin: FractionalOffset(1, 0), end: FractionalOffset(-1, 0)),
          boxShadow: [
            BoxShadow(
                color: Color.fromRGBO(0, 0, 0, 0.5),
                offset: Offset(-10.0, 0.0),
                blurRadius: 70.0,
                spreadRadius: 20.0),
          ],
        ),
        constraints: BoxConstraints.expand(
            width: 202, height: MediaQuery.of(context).size.height),
        child: Padding(
          padding: EdgeInsets.fromLTRB(24, 26, 24, 26),
          child: child,
        ),
      ),
    );
  }

  Widget getRightMenu() {
    Widget rs;
    if ((_isFullScreen || _operFullScreen) && isShowRightMenu) {
      Widget subWidget;
      subWidget = Row(
        children: <Widget>[
          Column(
            children: <Widget>[
              Text('播放模式'),
              FlatButton(
                child: Text('顺序播放'),
                onPressed: () {
                  print('顺序播放');
                },
              ),
              FlatButton(
                child: Text('重复当前'),
                onPressed: () {
                  print('重复当前');
                },
              ),
            ],
          )
        ],
      );
      rs = getRightPopMenu(subWidget);
    } else {
      rs = rs = Container(
        child: Text(''),
      );
    }
    return rs;
  }

  ///清晰度列表视图
  Widget getVideTypeList() {
    Widget rs;
    if ((_isFullScreen || _operFullScreen) && isShowVideoTypeList) {
      Widget subWidget;
      subWidget = ListView.builder(
          itemCount: widget.path[_currentIndex].list.length,
          itemBuilder: (BuildContext context, int index) {
            return GestureDetector(
              child: Container(
                  alignment: Alignment.centerLeft,
                  margin: EdgeInsets.fromLTRB(6, 18, 0, 18),
                  child: Center(
                    child: GestureDetector(
                      child: Text(
                        widget.path[_currentIndex].list[index].name,
                        softWrap: true,
                        maxLines: 1,
                        overflow: TextOverflow.ellipsis,
                        style: index == _currentVideoTypeIndex
                            ? TextStyle(
                                fontSize: 18,
                                height: 1.5,
                                color: Color.fromRGBO(236, 115, 100, 1))
                            : TextStyle(
                                fontSize: 18,
                                height: 1.5,
                                color: Color.fromRGBO(255, 255, 255, 0.5)),
                      ),
                      onTap: () {
                        playVideoTypeWithIndex(index);
                      },
                    ),
                  )),
              onTap: () {},
            );
          });
      rs = getRightPopMenu(subWidget);
    } else {
      rs = rs = Container(
        child: Text(''),
      );
    }
    return rs;
  }

  ///播放列表视图
  Widget getPlayerList() {
    Widget rs;
    if ((_isFullScreen || _operFullScreen) && _openList) {
      Widget subWidget;
      subWidget = ListView.builder(
          itemCount: widget.path.length,
          itemBuilder: (BuildContext context, int index) {
            return GestureDetector(
              child: Container(
                  alignment: Alignment.centerLeft,
                  margin: EdgeInsets.fromLTRB(6, 18, 0, 18),
                  child: GestureDetector(
                    child: Text(
                      widget.path[index].title,
                      softWrap: true,
                      maxLines: 2,
                      overflow: TextOverflow.ellipsis,
                      style: index == _currentIndex
                          ? TextStyle(
                              fontSize: 18,
                              height: 1.5,
                              color: Color.fromRGBO(236, 115, 100, 1))
                          : TextStyle(
                              fontSize: 18,
                              height: 1.5,
                              color: Color.fromRGBO(255, 255, 255, 0.5)),
                    ),
                    onTap: () {
                      playVideoWithIndex(index);
                    },
                  )),
              onTap: () {},
            );
          });
      rs = getRightPopMenu(subWidget);
    } else {
      rs = rs = Container(
        child: Text(''),
      );
    }
    return rs;
  }

  //播放指定清晰度视频
  void playVideoTypeWithIndex(int index) {
    print('play video type index = $index');

    palyerController.pause();
    setState(() {
      //初始化之前可以保存
      // _currentValue = 0 ;
      _currentVideoTypeIndex = index;
    });
    // palyerController.dispose();
    initVideoPlayer(_currentIndex, index, true);
  }

  //播放指定视频
  void playVideoWithIndex(int index) {
    print('play video index = $index');

    palyerController.pause();
    setState(() {
      //初始化之前可以保存
      _currentValue = 1;
      _currentIndex = index;
      _currentVideoTypeIndex = widget.path[_currentIndex].list.length - 1;
    });
    // palyerController.dispose();
    initVideoPlayer(index, _currentVideoTypeIndex, true);
  }

  ///控制清晰度按钮是否显示
  Widget getVideoTypeFunction() {
    Widget rs;
    if ((_isFullScreen || _operFullScreen)) {
      rs = Container(
        key: _tapButtonWidget,
        width: 40,
        child: FlatButton(
          padding: EdgeInsets.all(0),
          child: Text(
            widget.path[_currentIndex].list[_currentVideoTypeIndex].name,
            style: TextStyle(
              color: Colors.white,
              fontSize: 14,
            ),
          ),
          onPressed: () {
            setState(() {
              isShowVideoTypeList = true;
            });
            print('清晰度选择');
          },
        ),
      );
    } else {
      rs = rs = Container(
        child: Text(''),
      );
    }
    return rs;
  }

  ///控制选集按钮是否显示
  Widget getPlayerListFunction() {
    Widget rs;
    if ((_isFullScreen || _operFullScreen) && widget.path.length > 1) {
      rs = Container(
        width: 64,
        padding: EdgeInsets.fromLTRB(8, 0, 16, 0),
        child: FlatButton(
          padding: EdgeInsets.all(0),
          child: Text(
            '选集',
            style: TextStyle(
              color: Colors.white,
              fontSize: 14,
            ),
          ),
          onPressed: () {
            if (openPannel) {
              setOSState(false);
              playerPannelController.reverse();
            }
            setState(() {
              _openList = true;
            });
          },
        ),
      );
    } else {
      rs = rs = Container(
        child: Text(''),
      );
    }
    return rs;
  }

  Widget getOrientationFunction() {
    Widget rs;
    if (!_isFullScreen && !_operFullScreen && widget.isMaxDisplay) {
      rs = Container(
        width: 64,
        padding: EdgeInsets.fromLTRB(8, 0, 16, 0),
        child: FlatButton(
          padding: EdgeInsets.all(0),
          child: Text(
            '横屏',
            style: TextStyle(
              color: Colors.white,
              fontSize: 14,
            ),
          ),
          onPressed: () {
            widget.backCall(true);
            setState(() {
              _operFullScreen = true;
            });
          },
        ),
      );
    } else {
      rs = Container(
        child: Text(''),
      );
    }
    return rs;
  }

  @override
  void initState() {
    super.initState();

    _currentIndex = widget.curIndex;
    _currentValue = widget.currentValue;
    _currentVideoTypeIndex = widget.path[_currentIndex].list.length - 1;
    isPlaying = widget.isPlay;

    setState(() {
      _isFullScreen = widget.isFullScreen;
    });
    playerPannelController = AnimationController(
      duration: Duration(milliseconds: 500),
      vsync: this,
    );
    playerTopPannelAnimation = CurvedAnimation(
        parent: playerPannelController, curve: Curves.easeInBack);
    playerTopPannelAnimation.addListener(() {
      setState(() {});
    });
    playerTopPannelInfoAnimation = CurvedAnimation(
        parent: playerPannelController, curve: Curves.easeInBack);
    playerTopPannelAnimation.addListener(() {
      setState(() {});
    });
    playerBottomPannelAnimation = CurvedAnimation(
        parent: playerPannelController, curve: Curves.easeInBack);
    playerBottomPannelAnimation.addListener(() {
      setState(() {});
    });
    playerBottomPannelInfoAnimation = CurvedAnimation(
        parent: playerPannelController, curve: Curves.easeInBack);
    playerBottomPannelAnimation.addListener(() {
      setState(() {});
    });

    playerPannelController.addStatusListener((status) {
      // if (status == AnimationStatus.completed) {
      //   playerPannelController.reverse();
      // } else if (status == AnimationStatus.dismissed) {
      //   playerPannelController.forward();
      // }
      // print("status====$status");
    });

    operatePannel();

    //****************播放器 */
    initVideoPlayer(_currentIndex, _currentVideoTypeIndex, widget.isPlay);

    subscription = OrientationPlugin.onOrientationChange.listen((value) {
      if (!mounted) return;
      setState(() {
        _deviceOrientation = value;
      });
    });
  }

  void initVideoPlayer(int videoIndex, int videoTypeIndex, bool isAutoPlay) {
    // _disposeVideoController();
    //network 、 asset、 file
    switch (widget.sourceType) {
      case 'network':
        palyerController = VideoPlayerController.network(
            widget.path[videoIndex].list[videoTypeIndex].url);
        break;
      case 'file':
        palyerController = VideoPlayerController.file(
            File(widget.path[videoIndex].list[videoTypeIndex].url));
        break;
      case 'asset':
        palyerController = VideoPlayerController.asset(
            widget.path[videoIndex].list[videoTypeIndex].url);
        break;
      default:
        palyerController = VideoPlayerController.network(
            widget.path[videoIndex].list[videoTypeIndex].url);
    }

    palyerController.initialize().then((_) {
      setState(() {
        videoAllTimes = palyerController.value.duration.inSeconds;
      });
      print('初始化完成');
      palyerController.addListener(() {
        palyerController.position.then((pos) {
          setState(() {
            _currentValue = pos.inSeconds.toInt();
          });

          setState(() {
            isPlaying = palyerController.value.isPlaying;
          });
          // print('isPlaying' + isPlaying.toString());

          // print(DateTime.now().toString() +
          //     ':: current pos (sec) : ' +
          //     pos.inSeconds.toDouble().toString() +
          //     '   毫秒: ' +
          //     (pos.inMicroseconds.toDouble() / 1000).toString());
        });
      });

      if (_currentValue != 0 && isAutoPlay) {
        print('开始继续播放');
        palyerController.seekTo(Duration(seconds: _currentValue));
        palyerController.play();
      } else if (isAutoPlay) {
        print('开始播放');
        palyerController.play();
      } else {
        palyerController.pause();
      }
    });

    //palyerController.setVolume(0.3); 默认1，范围0-1；
  }

  _disposeVideoController() {
    if (palyerController != null) {
      palyerController.dispose();
      palyerController = null;
    }
  }

  void operatePannel() {
    if (_openList) {
      setState(() {
        _openList = false;
      });
    }

    //osStateInfo = [SystemUiOverlay.top, SystemUiOverlay.bottom];
    if (openPannel) {
      setOSState(false);
      playerPannelController.reverse();
      openPannel = false;
      timerNum = 1; //手动关闭
    } else {
      playerPannelController.forward();
      setOSState(true);
      //10s 后自动动画回滚
      var duration = new Duration(seconds: 10);
      Future.delayed(duration, () {
        if (timerNum != 1 && playerPannelController != null) {
          playerPannelController.reverse();
          setOSState(false);
          openPannel = false;
        }
        timerNum = 0; //自动关闭
      });
      openPannel = true;
    }
  }

  void setOSState(bool open) {
    if ((_deviceOrientation == DeviceOrientation.landscapeLeft ||
            _deviceOrientation == DeviceOrientation.landscapeRight) &&
        !open) {
      setState(() {
        osStateInfo = [];
      });
    } else {
      setState(() {
        osStateInfo = [SystemUiOverlay.top, SystemUiOverlay.bottom];
      });
    }
  }

  //依托父级控件浮层示例，暂不使用。
  OverlayEntry showVideoTypeView(BuildContext context) {
    //屏幕宽高
    RenderBox renderBox = context.findRenderObject();
    var screenSize = renderBox.size;
    //触发事件的控件的位置和大小
    renderBox = _tapButtonWidget.currentContext.findRenderObject();
    var parentSize = renderBox.size;
    var parentPosition = renderBox.localToGlobal(Offset.zero);
    //正式创建Overlay
    return OverlayEntry(
        builder: (context) => Positioned(
              top: parentPosition.dy - parentSize.height,
              left: parentPosition.dx,
              width: 300,
              // height: 300, 自动高度
              // screenSize.height -
              //     parentPosition.dy -
              //     parentPosition.distance,
              child: Stack(children: <Widget>[
                GestureDetector(
                  onTap: () {},
                  child: Container(
                    height: screenSize.height -
                        parentPosition.dy -
                        parentPosition.direction,
                    width: screenSize.width,
                    color: Colors.black26,
                    child: Text('高清'),
                  ),
                ),
                Container(height: 100), //悬浮窗口自定义
              ]),
            ));
  }

  _showOverlay(bool isShow) {
    if (isShow) {
      videoTypeListOverlay = showVideoTypeView(context);
      Overlay.of(context).insert(videoTypeListOverlay);
    } else {
      if (isShowVideoTypeList) {
        videoTypeListOverlay.remove();
        setState(() {
          isShowVideoTypeList = false;
        });
      }
    }
  }

  @override
  void dispose() {
    if (_isFullScreen) {
      AutoOrientation.portraitUpMode();
    } else {
      if (_operFullScreen) {
        widget.backCall(false);
        setState(() {
          _operFullScreen = false;
        });
      }
    }

    playerPannelController.dispose();
    _disposeVideoController();
    super.dispose();
  }
}

class PlayerInputInstance {
  String title;
  List<VideoType> list;
  int currentValue;

  PlayerInputInstance({
    this.title,
    this.list,
    this.currentValue = 0,
  });
}

class VideoType {
  String name;
  String url;

  VideoType({
    this.name,
    this.url,
  });
}
